import React, { useState, useEffect } from 'react';
import Post from '../components/Post';
import { ReactComponent as DeleteIcon } from '../assets/icons/Delete.svg';
import { useParams , useNavigate } from 'react-router-dom';
import { getBlogById, deleteBlog } from '../api/userApi'; // 导入删除接口
import './PostDetail.css';

const PostDetail = () => {
  const { blogId } = useParams(); // 从路由参数获取 blogId
  const [postData, setPostData] = useState(null); // 状态保存帖子数据
  const [loading, setLoading] = useState(true); // 加载状态
  const [error, setError] = useState(null); // 错误状态
  const navigate = useNavigate(); // 初始化 navigate

  useEffect(() => {
    const fetchPostData = async () => {
      try {
        const userId = localStorage.getItem('userId'); // 获取当前用户 ID
        const data = await getBlogById(blogId, userId); // 传递 userId 作为参数
        console.log('postData:', data);
        setPostData(data); // 将获取到的数据保存到状态
      } catch (err) {
        setError(err.message); // 处理错误
      } finally {
        setLoading(false); // 设置加载状态完成
      }
    };

    fetchPostData(); // 调用获取数据的函数
  }, [blogId]); // 当 blogId 改变时重新请求数据

  const handleDelete = async () => {
    const result = await deleteBlog(blogId); // 调用删除接口
    if (result.success) {
      alert(result.message); // 删除成功提示
      // 在这里可以加上跳转到其他页面或更新界面的逻辑
      navigate(-1); // 返回到前一页
    } else {
      alert(result.error); // 删除失败提示
    }
  };

  if (loading) {
    return <div>加载中...</div>; // 显示加载状态
  }

  if (error) {
    return <div>错误: {error}</div>; // 显示错误信息
  }

  if (!postData) {
    return <div>帖子不存在</div>; // 显示帖子不存在的提示
  }

  // 渲染博客数据
  const post = {
    userId: postData.userId,
    userImage: postData.userImage,
    blogImage: postData.blogImage,
    blogId: postData.blogId,
    interestId: postData.interestId,
    title: postData.name,
    author: postData.account,
    content: postData.description,
    time: postData.updateTime,
    likeCount: postData.likesCount,
    commentCount: postData.commentsCount,
    isLiked: postData.isLiked,
    isFollowed: postData.isFollowed,
    isCollected: postData.isCollected,
  };

  // 获取当前用户 ID
  const currentUserId = localStorage.getItem('userId');
  console.log('currentUserId:', currentUserId);
  console.log('postUser:', post.userId);

  return (
    <div className="post-detail-container">
      {/* 直接引用 Post 组件，并传入 postData 作为 props */}
      <Post post={post} isDetailPage={true} style={{ width: '100%' }} />
      
      {/* 判断是否显示删除按钮 */}
      {String(post.userId) === currentUserId && (
        <div>
          <button className="delete-button" onClick={handleDelete}>
            <DeleteIcon className='delete-icon'/>
            <span>删除</span>
          </button>
        </div>
      )}
    </div>
  );
};

export default PostDetail;
